import { h } from 'vue'
import myComponent from './myComponent.vue'
export default {
  props: ['config'],
  components: {
    myComponent
  },
  created () {
    if (typeof this.config === 'object') {
      const { fields, ...formConfig } = this.config
      this.fields = fields
      this.formConfig = formConfig
    } else if (typeof this.config === 'function') {
      this.config().then(res => {
        const { fields, ...formConfig } = res
        this.fields = fields
        this.formConfig = formConfig
      })
    }
  },
  data (){
    return {
      form: {},
      fields: [],
      formConfig: {},
    }
  },
  methods: {
    renderBase(type, props){
      h(type, props)
    },
    createComponent (type, param, props) {
      const { options = [] } = props
      if (type === 'select'){
        return <el-select v-model={ this.form[param] } { ...props } style="width: 100%">
          { options.map(option => <el-option label={ option.label } value={ option.value } />) }
        </el-select>
      } else if (type === 'radio'){
        return <el-radio-group v-model={ this.form[param] } { ...props }>
          { options.map(option => <el-radio label={ option.label } value={ option.value } />) }
        </el-radio-group>
      } else if (type === 'checkbox'){
        return <el-checkbox-group v-model={ this.form[param] } { ...props }>
          { options.map(option => <el-checkbox label={ option.label } value={ option.value } />) }
        </el-checkbox-group>
      } else {
        return <myComponent v-model={ this.form[param] } tagName= {type} { ...props } style="width: 100%"/>
      }
    },
    renderFields() {
      const fields = this.fields.map(field => {
        const { param, type, width, props = {}, ...config } = field
        return <div style={ `width: ${width || '100%'}` }><el-form-item { ...config }>{ this.createComponent(type, param, props) }</el-form-item></div>
      })
      return fields
    }
  },
  render(){
    return <el-form { ...this.formConfig } style="display: flex; flex-wrap: wrap;padding: 20px 100px 20px 20px;">{ this.renderFields() }</el-form>
  }
}